<template>
  <div id="order" class="container" v-loading="loading">
    <el-tabs
      v-model="activeName"
      class="tabs"
      type="card"
      @tab-click="handleClick"
    >
      <el-tab-pane
        v-for="item in langList"
        :key="item.id"
        :label="item.lang"
        :name="item.lang"
      />
    </el-tabs>

    <div class="content">
      <div class="search_content">
        <el-form inline>
          <el-form-item label="文章标题：">
            <el-input
              v-model="formData.title"
              placeholder="请输入文章标题"
              size="small"
            />
          </el-form-item>
          <el-form-item label="栏目：">
            <el-select
              v-model="formData.category_id"
              multiple
              clearable
              filterable
            >
              <el-option
                v-for="item in columnDataSource"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态：">
            <el-select v-model="formData.status">
              <el-option
                v-for="(label, value) in articleTypeEnums"
                :key="value"
                :label="label"
                :value="value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getContent">
              搜索
            </el-button>
            <el-button size="small" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="top">
        <h3 class="title">
          <span />
          栏目内容管理
        </h3>
        <div class="topbtn">
          <el-button
            type="primary"
            class="orange"
            size="mini"
            icon="el-icon-plus"
            style="margin-left: 15px"
            @click="handleRouterContent"
          >
            新增内容
          </el-button>
          <el-dropdown trigger="click" @command="handleCommand">
            <span class="el-dropdown-link el-icon-paperclip">查看副表</span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="item in moduleData"
                :key="item.id"
                :command="item.id"
              >
                {{ item.title }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            type="primary"
            size="mini"
            class="blue"
            style="margin-left: 15px"
            @click="handleOffline()"
          >
            批量禁用
          </el-button>
          <el-button
            type="primary"
            size="mini"
            class="tianBlue"
            style="margin-left: 15px"
            @click="handleDelete()"
          >
            批量删除
          </el-button>
          <UploadFiles
            :loading.sync="loading"
            :lang="activeName"
            @success="handleReset"
          ></UploadFiles>
        </div>
      </div>
      <div class="flex">
        <el-table
          :data="contentData"
          border
          stripe
          :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column label="ID" prop="id" width="55" />
          <el-table-column label="标题" prop="title" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-link :href="scope.row.url" target="_blank">
                {{ scope.row.title }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="副标题" width="120px">
            <template slot-scope="scope">
              <el-popover
                placement="top-start"
                title=""
                width=""
                trigger="click"
                :content="scope.row.sub_title"
              >
                <span slot="reference" class="subTitle">
                  {{ scope.row.sub_title }}
                </span>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="栏目" width="120px">
            <template slot-scope="scope">
              {{ getCategoryName(scope.row.category) }}
            </template>
          </el-table-column>
          <el-table-column label="排序" prop="sort" width="60px" />

          <el-table-column label="状态" width="150px">
            <template slot-scope="scope">
              {{ articleTypeEnums[scope.row.new_status] }}
            </template>
          </el-table-column>
          <el-table-column label="缩略图" width="100px">
            <template slot-scope="scope">
              <el-image
                v-if="scope.row.thumbnail"
                style="width: 100%; height: auto"
                :src="scope.row.thumbnail.url"
                :fit="'cover'"
                :preview-src-list="[scope.row.thumbnail.url]"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <!-- <el-table-column label="创建时间" prop="create_time" width="160px" /> -->
          <el-table-column label="发布时间" prop="publish_time" width="160px" />
          <el-table-column
            label="当前处理人"
            prop="check_users"
            width="100px"
          />
          <el-table-column label="点击量" prop="hits" width="70px" />
          <el-table-column label="操作" fixed="right" width="280px">
            <template slot-scope="scope">
              <el-button class="edit" size="mini" @click="editor(scope.row)">
                编辑
              </el-button>
              <el-button
                v-if="scope.row.new_status === 1"
                size="mini"
                @click="handleOffline(scope.row.id)"
              >
                禁用
              </el-button>

              <el-button
                v-if="scope.row.new_status === 5"
                size="mini"
                @click="handleOffline(scope.row.id, 'online')"
              >
                启用
              </el-button>
              <el-button
                class="tianBlue"
                size="mini"
                type="primary"
                @click="handleCopy(scope.row)"
              >
                复制
              </el-button>
              <el-button
                class="dele"
                size="mini"
                @click="handleDelete(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="page.currentPage"
          :page-sizes="page.pageSizes"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          :hide-on-single-page="page.total < page.size ? true : false"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>
<script>
import columnApi from '@/api/column.js'
import contentApi from '@/api/module'
import websetApi from '@/api/websetting'
import { articleTypeEnums } from '@/enums/article'
import UploadFiles from './components/uploadFiles.vue'
export default {
  components: { UploadFiles },
  data() {
    return {
      loading: false,
      articleTypeEnums,
      columnDataSource: [],
      formData: {
        title: '' // 搜索标题
      },
      list: [],
      options: [], // 站点
      contentData: [], // 内容
      moduleData: '',
      checkedKeys: [],
      page: {
        total: 0,
        currentPage: 1,
        size: 10,
        pageSizes: [10, 20, 30, 40]
      }, // 分页器
      val: {},
      totalAmount: '',
      category_id: '',
      activeName: '',
      langList: [],
      tableSelectionData: [] // table 选中数据
    }
  },
  computed: {
    siteId1() {
      return this.$store.getters.siteId
    }
  },
  watch: {
    siteId1(val, value) {
      this.siteId = val
      this.getLang()
    }
  },
  created() {
    this.siteId = this.$store.getters.siteId
    this.getModule()
    this.getLang()
  },
  methods: {
    handleSelectionChange(val) {
      this.tableSelectionData = val
    },
    // 批量删除
    async handleDelete(id) {
      if (!id) {
        if (!this.tableSelectionData.length) {
          this.$message.error('请先选中数据')
          return
        }
      }
      const res = await this.$confirm(
        '此操作将该内容放入回收站, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }
      ).catch(err => console.log(err))
      if (res) {
        const ids = this.tableSelectionData.map(item => item.id)
        const result = await columnApi.deleteContent({
          ids: id || ids
        })
        if (result.code == 0) {
          this.$message.success('操作成功！')
          this.getContent()
        }
      }
    },
    // 批量禁用
    async handleOffline(id, type) {
      if (!id) {
        if (!this.tableSelectionData.length) {
          this.$message.error('请先选中数据')
          return
        }
      }
      const res = await this.$confirm(
        `此操作将该内容${type === 'online' ? '启用' : '禁用'}, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }
      ).catch(err => console.log(err))
      if (res) {
        const ids = this.tableSelectionData.map(item => item.id)
        const result = await columnApi.changeContentStatus({
          id: id || ids,
          status: type === 'online' ? 1 : 2
        })
        if (result.code == 0) {
          this.$message.success('操作成功！')
          this.getContent()
        }
      }
    },
    handleReset() {
      this.formData = {}
      this.page = {
        ...this.page,
        currentPage: 1,
        size: 10
      }
      this.getContent()
    },
    getCategoryName(row) {
      return row.map(item => item.title).join(',')
    },
    handleRouterContent() {
      this.$router.push({
        name: 'addContent',
        query: {
          lang: this.activeName
        }
      })
    },
    async getCategoryList() {
      const res = await contentApi.getModuleCate({
        site_id: [this.siteId],
        lang: this.activeName,
        ...this.formData
      })
      this.columnDataSource = res.data?.[0]?.category || []
    },
    topOpt(row) {
      const val = {
        id: row.id,
        is_top: row.is_top
      }
      columnApi.topOpt(val).then(res => {
        if (res.code == 0) {
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    recommend(row) {
      const val = {
        id: row.id,
        is_recommend: row.is_recommend,
        type: 'recommend'
      }
      columnApi.recommendAndStatus(val).then(res => {
        if (res.code == 0) {
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 获取站点语言
    getLang() {
      websetApi.langInfo({ site_id: this.siteId }).then(res => {
        this.langList = res.data

        if (res.data.length > 0) {
          this.activeName = res.data[0].lang
        }
        this.getCategoryList()
        this.getContent()
      })
    },
    // tab切换
    handleClick(val) {
      this.activeName = val.name
      this.getCategoryList()
    },

    // 栏目内容列表
    getContent() {
      const val = {
        page: this.page.currentPage,
        limit: this.page.size,
        lang: this.activeName,
        website_id: this.siteId,
        ...this.formData
      }
      columnApi.contentList(val).then(res => {
        this.contentData = res.data
        this.page.total = res.count
        this.list = []
        // 表格数据  drawerTableList
        // 获取每张图片的地址
        for (var x = 0; x < this.contentData.length; x++) {
          if (this.contentData[x].thumbnail != null) {
            this.list.push(this.contentData[x].thumbnail.url)
          }
        }
        // 根据图片顺序（index）更改每张图片绑定的list的图片顺序
        for (var i = 0; i < this.contentData.length; i++) {
          // this.list.push(this.drawerTableList[i].path)
          var container = this.list

          var frontArr = container.slice(0, i)
          var behindArr = container.slice(i, this.contentData.length)
          var list = behindArr.concat(frontArr)
          this.contentData[i].list = list
        }
      })
    },
    getModule() {
      contentApi.moduleList({ website_id: this.website_id }).then(res => {
        this.moduleData = res.data
      })
    },
    // 查看副表
    handleCommand(val) {
      this.$router.push({
        name: 'ColumnInfo',
        query: { id: val, website_id: this.siteId }
      })
    },
    // 复制
    handleCopy(row) {
      console.log(row.module_id)
      this.$router.push({
        name: 'updateContent',
        query: {
          id: row.id,
          lang: this.activeName,
          module_id: row.module_id,
          website_id: this.siteId,
          type: 'copy'
        }
      })
    },
    // 编辑
    editor(row) {
      const val = {
        id: row.id,
        module_id: row.module_id,
        lang: this.activeName,
        website_id: this.siteId
      }
      columnApi.contentInfo(val).then(res => {
        if (res.code == 0) {
          const website = res.data.content.website
          const category = res.data.content.category
          this.$router.push({
            name: 'updateContent',
            query: {
              id: row.id,
              category_id: category,
              module_id: row.module_id,
              lang: this.activeName,
              siteId: website
            }
          })
        }
      })
    },
    // 查看
    check(row) {
      this.$router.push({ name: 'ColumnInfo', query: { id: this.siteId } })
    },
    // 分页规格改变
    handleSizeChange(val) {
      this.page.size = val
      this.page.currentPage = 1
      this.getContent()
    },
    // 分页点击
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.getContent()
    }
  }
}
</script>
<style lang="scss">
#order {
  .el-date-editor.el-input.el-date-editor--date {
    width: 180px;
  }
}
.tabs.el-tabs--card > .el-tabs__header .el-tabs__item {
  background-color: #eee;
  border: none;
  margin-right: 5px;
}
.tabs.el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
  background-color: #fff;
}
.tabs.el-tabs--card > .el-tabs__header .el-tabs__nav {
  border-radius: 0;
  border: none;
}
.tabs.el-tabs--card .el-tabs__header {
  margin: 0;
}
.tabs.el-tabs--card > .el-tabs__header {
  border-bottom: 0;
}
</style>
<style scoped lang="scss">
.search_content {
  display: inline-block;
  margin: 0 20px;
  label {
    font-weight: normal;
    font-size: 14px;
    margin-right: 10px;
  }
  .el-input {
    width: 300px;
    margin-right: 10px;
  }
  .el-button {
    display: inline-block;
  }
}
.content {
  background-color: #fff;
  padding-top: 20px;
}
.el-table {
  margin-bottom: 20px;
}
.search {
  min-width: 1350px;
  background-color: #fff;
  padding: 35px 30px 20px;
  border-radius: 5px;
}
.flex {
  .tree {
    width: 300px;
    margin-right: 20px;
    background-color: #fff;
    h4 {
      padding: 15px;
      border-bottom: solid 1px #eee;
      font-size: 15px;
    }
    .el-tree {
      padding: 15px;
    }
  }
}
.top {
  display: flex;
  h3.title {
    width: 320px;
  }
  .topbtn {
    margin-bottom: 20px;
    .el-dropdown-link {
      //模拟按钮
      cursor: pointer;
      color: #fff;
      background-color: #f84311;
      padding: 8.5px 17px;
      font-size: 12px;
      border-radius: 19px;
      margin-left: 15px;
    }
  }
}
.subTitle {
  cursor: pointer;
  overflow: hidden;
  display: -webkit-box;
  text-overflow: ellipsis;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  white-space: normal;
}
</style>
